import * as React from 'react';
import {observer} from 'mobx-react'
import styles from './index.scss';
import Test from '../test/index'
import Second from '../second/index'

interface IProps {
}

interface IState {
    isLoading: any
}

const neverResolve = new Promise(() => {
});

function Suspender({suspend}) {
    if (suspend) {
        throw neverResolve;
    } else {
        return null;
    }
}

function Preload({show, children}) {
    return (
        <React.Suspense fallback={null}>
            {children}
            <Suspender suspend={!show} />
        </React.Suspense>
    );
}

@observer
class Home extends React.Component<IProps, IState> {

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true
        }
    }

    public componentDidMount() {
        window.addEventListener('hashchange', this.handleHash)
    }

    public handleHash = () => {
        const url = window.location.hash
        if (url === '#/second') {
            this.setState({
                isLoading: null
            })
        } else if (url === '#/') {
            this.setState({
                isLoading: true
            })
        }
    }

    public render() {
        const {isLoading} = this.state
        return (
            <div className={styles.container}>
                <Preload show={isLoading !== null}>
                    <Test />
                </Preload>

                <Preload show={isLoading === null}>
                    <Second />
                </Preload>

            </div>
        );
    }
}

export default Home;
